#include <iostream>
#include <termios.h>
#include <stdio.h>      // printf
#include <fcntl.h>      // O_RDWR
#include <string.h>     // memset
#include <cstdlib>      // system
#include <time.h>
#include "frskyTx.h"

using namespace std;

int openSerial (char* port) {
    int fd;
    struct termios tio;

    memset (&tio, 0, sizeof (tio));
    tio.c_iflag = 0;
    tio.c_oflag = 0;
    tio.c_cflag = CS8|CREAD|CLOCAL;
    tio.c_lflag = 0;
    tio.c_cc[VMIN] = 1;
    tio.c_cc[VTIME] = 5;

    fd = open (port, O_RDWR | O_NONBLOCK);
    cfsetospeed (&tio, B9600);
    cfsetispeed (&tio, B9600);

	if (fd == -1 ) {
		cout << "open_port: Unable to open " << port << endl;
		exit (2);
	}
    return fd;
}

int main (int argc, char* argv[]) {

    time_t ltime;
    struct tm *tm;
    int fd = openSerial (argv[1]);

    int cell = 0;

    frskyTx ftx;

    ftx.setAmpAmp (50);
    ftx.setRpm (2000);    // 2000 = 1000 RPM / 2 blades
    ftx.setAltitude (101);
    ftx.setTemp1 (20);
    ftx.setTemp2 (20);
    ftx.setAccX (1);
    ftx.setAccY (1);
    ftx.setAccZ (1);
    ftx.setFuel (50);
    ftx.setGpsSpeedKmh (100.0);
    //ftx.setGpsAltitude ();

    while (1) {
        if (cell > 2) cell = 0;
        ftx.setLipo (cell++, 3.70);

        ftx.setAmpVolt (ftx.getLipoVoltSum());

        ltime = time (NULL);
        tm = localtime (&ltime);
        ftx.setHourMinSec (tm->tm_hour, tm->tm_min, tm->tm_sec);

        ftx.sendFrame1 (fd);
        ftx.sendFrame2 (fd);
        ftx.sendFrame3 (fd);
        cout << endl;
        sleep (1);
    }

    return 0;
}
